// Load required modules
var http = require("http"); // http server core module
const path = require('path');
var express = require("express"); // web framework external module
const proxy = require('express-http-proxy');
const config = require('./config');
const helmet = require('helmet');
const compression = require('compression')
var serveStatic = require('serve-static'); // serve static files
var socketIo = require("socket.io"); // web socket external module
var easyrtc = require("easyrtc"); // EasyRTC external module
var fs = require('fs'); //文件模块
var qs=require('querystring');

const port = config.port || process.env.PORT;

// Set process name
process.title = "node-easyrtc";

// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();
// app.use(serveStatic('src', { 'index': ['index.html'] }));
// app.use('/node_modules', express.static(__dirname + '/node_modules/'));

// 设置 HTTP 头
// reference: http://expressjs.com/zh-cn/advanced/best-practice-security.html
app.use(helmet());

// 开启 gzip 压缩
// reference: http://expressjs.com/zh-cn/advanced/best-practice-performance.html
app.use(compression());


app.use(express.static(path.join(__dirname, 'dist')));

const bodyParser = require('body-parser');
app.use(bodyParser.json());//数据JSON类型
app.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据

//获取前端访问地址
app.get('/web/getserver/webServer',function(req,res){
    res.json({status:'OK',webServer:'http://localhost:'+config.port});
  })
//node生成json文件
app.post('/web/addJsonFile', function(req, res) {
    // var fileName = req.body.fileName;
    //console.log("参数1111："+req.body.jsonData+"====文件名："+req.body.fileName);
    var file = path.join(__dirname, '/assets/i18n/'+req.body.fileName+'.json'); 
    //写入文件
    fs.writeFile(file,req.body.jsonData, function(err) {
        if (err) {
            console.log("创建文件zh.json失败!"+err);
        }
    }); 
    res.json({status:'OK'});
});
var createFolder = function(folder){
    try{
        fs.accessSync(folder); 
    }catch(e){
        fs.mkdirSync(folder);
    }  
  };
  
  var uploadFolder = './upload/';


app.use('/market', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/market" + req.url).path;
    }
}));
app.use('/eas', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/eas" + req.url).path;
    }
}));
app.use('/esl', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/esl" + req.url).path;
    }
}));
app.use('/smartshelf', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/smartshelf" + req.url).path;
    }
}));
app.use('/fitroom', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/fitroom" + req.url).path;
    }
}));
app.use('/unlock', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/unlock" + req.url).path;
    }
}));
app.use('/autopay', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/autopay" + req.url).path;
    }
}));
app.use('/assets', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/assets" + req.url).path;
    }
}));
app.use('/material', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/material" + req.url).path;
    }
}));
app.use('/picture', proxy(config.api, {
    proxyReqPathResolver: function(req, res) {
        console.log(req.url);
        console.log(require('url').parse("" + req.url).path);
        return require('url').parse("/picture" + req.url).path;
    }
}));
app.get('*', function(req, res) {
    res.sendFile(__dirname + '/dist/index.html');
});

// Start Express http server on port
var webServer = http.createServer(app).listen(port);

// Start Socket.io so it attaches itself to Express server
var socketServer = socketIo.listen(webServer, { "log level": 1 });

easyrtc.setOption("logLevel", "debug");

// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
    easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj) {
        if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) {
            callback(err, connectionObj);
            return;
        }

        connectionObj.setField("credential", msg.msgData.credential, { "isShared": false });

        console.log("[" + easyrtcid + "] Credential saved!", connectionObj.getFieldValueSync("credential"));

        callback(err, connectionObj);
    });
});

// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
    console.log("[" + connectionObj.getEasyrtcid() + "] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
    easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});

// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer, null, function(err, rtcRef) {
    console.log("Initiated");

    rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
        console.log("roomCreate fired! Trying to create: " + roomName);

        appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
    });
});

//listen on port
webServer.listen(port, function() {
    console.log('listening on http://localhost:' + port);
});